package com.sanjiayi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sanjiayi.mapper.ChatMessageMapper;
import com.sanjiayi.pojo.ChatMessage;
import com.sanjiayi.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Override
    @Transactional
    public void saveMessage(ChatMessage message) {
        chatMessageMapper.insert(message);
    }

    @Override
    public List<ChatMessage> getChatHistory(Integer userId1, Integer userId2, Integer limit) {
        QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.nested(w -> w
                .eq("sender_id", userId1).eq("receiver_id", userId2)
                .or()
                .eq("sender_id", userId2).eq("receiver_id", userId1)
            )
            .orderByDesc("create_time")
            .last(limit != null, "LIMIT " + limit);
        
        return chatMessageMapper.selectList(queryWrapper);
    }

    @Override
    public int getUnreadCount(Integer userId) {
        QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("receiver_id", userId)
                   .eq("is_read", false);
        Long count = chatMessageMapper.selectCount(queryWrapper);
        return count != null ? count.intValue() : 0;
    }

    @Override
    @Transactional
    public void markAsRead(Integer senderId, Integer receiverId) {
        ChatMessage updateEntity = new ChatMessage();
        updateEntity.setIsRead(true);
        
        QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sender_id", senderId)
                   .eq("receiver_id", receiverId)
                   .eq("is_read", false);
        
        chatMessageMapper.update(updateEntity, queryWrapper);
    }

    @Override
    public List<ChatMessage> getRecentChats(Integer userId) {
        return chatMessageMapper.selectRecentChats(userId);
    }
} 